import React, {Component,Fragment } from 'react';
import {Button, Card,Form, Input,Select,Upload ,Modal,message} from 'antd';
import {ArrowLeftOutlined,PlusOutlined,LoadingOutlined } from '@ant-design/icons';
import {reqProductView,reqAddProduct, reqUpdateProduct} from "../../../api/index.js"
import PicturesWall from '../PicturesWall'
// import RichTextEditor from "../RichTextEditor";
/**
 * 首页路由组件
 */
const {Option} = Select



export default class AddUpdate extends Component {
	  picturesWall = React.createRef();
	  // richTextEditor = React.createRef();
	  formRef = React.createRef();
	  
	   state = {
		 previewVisible: false,
		 categoryList:[],//商品分类的列表
		 title:'',//标题，新增或者修改
		 name:'',//商品名称
		 desc:'',//商品描述
		  price:0, //商品价格
		  categoryId:'', //分类id
		  detail:'', //商品详情
		  imgs:'',//图片
		
	    productInfo:{},
		   };
	   
	   componentDidMount=async()=>{
		   
	     const {id} = this.props.location.state || {};
		 if(id) {
			 const { status,data,msg} = await reqProductView(id)
			 if(status === 0) {
				const {name,desc, price, categoryId, detail, imgs} = data;
				this.setState({name,desc, price, categoryId, detail, imgs,title:'修改'},()=>{
					/*
					!这边是巨坑，需要注意,需要初始化表单列表
					*/
					this.formRef.current.resetFields();
					//回显照片
					this.picturesWall.current.setImgArr(imgs);
					//回显富文本
					// this.richTextEditor.current.setRichText(detail);
				})
			 }else {
				 message.error(msg,2);
			 }
		 }else {
			 this.setState({title:'添加'})
		 }

		 
	   }
	   handleFinish=async(values)=>{
		   const {id} = this.props.location.state || {};
		   if(id) {//修改逻辑 
		     const {categoryId, name, price, desc, productStatus} = values;
		     //获取图片
		     let imgArr = this.picturesWall.current.getImgArr();
		     const {
		         status,
		         msg
		     } = await reqUpdateProduct(categoryId, name, price, desc, productStatus, imgArr, id);
		     if (status === 0) {
		         //提示
		         message.success("更新商品成功", 2);
		         //跳转到商品管理页面
		         this.props.history.replace('/admin/products/product');
		     } else {
		         message.error(msg, 2);
		     }
			   
		   }else{//新增的逻辑
			   const {categoryId, name, price, desc, productStatus} = values;
			   //获取图片
			   let imgArr = this.picturesWall.current.getImgArr();
			
			   const {
			       status,
			       msg
			   } = await reqAddProduct(categoryId, name, price, desc, productStatus, imgArr);
			   if (status === 0) {
			       //提示
			       message.success("新增商品成功", 2);
			       //跳转到商品管理页面
			       this.props.history.replace('/admin/products/product');
			   } else {
			       message.error(msg, 2);
			   }
		   }
	   }
	   // handleChange = info => {
	     // if (info.file.status === 'uploading') {
	     //   this.setState({ loading: true });
	     //   return;
	     // }
	     // if (info.file.status === 'done') {
	     //   // Get this url from response in real world.
	     //   getBase64(info.file.originFileObj, imageUrl =>
	     //     this.setState({
	     //       imageUrl,
	     //       loading: false,
	     //     }),
	     //   );
	     // }
		  // this.setState({ fileList })
	   // };
	    // handleCancel = () => this.setState({ previewVisible: false });
    render() {
		  const {title, name, desc, price, categoryId,imgs,previewVisible,loading} = this.state;
		    const uploadButton = (
		      <div>
		        {loading ? <LoadingOutlined /> : <PlusOutlined />}
		        <div style={{ marginTop: 8 }}>Upload</div>
		      </div>
		    );
		  
        return (
            <div>
			    <Card title={
                <Fragment>
                    <Button size={"large"} type="link"
                            icon={<ArrowLeftOutlined onClick={() => {
                                this.props.history.goBack()
                            }}/>}>
                        <span> {`商品${title}`}</span>
                    </Button>
                </Fragment>
            }>
				      <Form name="control-hooks" style={{marginLeft:'60px',width:'70%'}} onFinish={this.handleFinish} ref={this.formRef}>
	
				           <Form.Item name="name"  label="商品名称" 
							initialValue={name || ''} 
							rules={[{required: true, whitespace: true, message: '请输入商品名称'}]}>
				             <Input autoComplete="off"  placeholder="请输入商品名称"/>
				           </Form.Item>
						   <Form.Item name="desc" label="商品描述"
						   initialValue={desc || ''}
						   rules={[{required: true, whitespace: true, message: '请输入商品描述'}]}>
						     <Input />
						   </Form.Item>
						   <Form.Item name="price" label="商品价格" 
						   initialValue={price || ''}
						   rules={[{required: true, whitespace: true, message: '请输入商品价格'}]}>
						     <Input  type="number" autoComplete="off"  addonBefore="￥" addonAfter="元" 
							 autoComplete="off"  placeholder="请输入商品名称"/>
						   </Form.Item>
				           <Form.Item name="gender" label="商品分类" rules={[{ required: true }]}>
				             <Select
				               placeholder="Select a option and change input text above"
				               allowClear 
				             >
				               <Option value="male">male</Option>
				               <Option value="female">female</Option>
				               <Option value="other">other</Option>
				             </Select>
				           </Form.Item>
						 <Form.Item label="商品图片" style={{marginLeft:'10px'}}>
						    <PicturesWall ref={this.picturesWall}/>
						 </Form.Item>
						  
						 <Form.Item label="商品详情" name="detail" >
						    商品详情
						 </Form.Item>
				           <Form.Item wrapperCol={{offset: 10}}>
				             <Button type="primary" htmlType="submit">
				               提交 
				             </Button>
				           </Form.Item>
				         </Form>
				</Card>        
            </div>
        );
    }
}
//  <img alt="example" style={{ width: '100%' }} src={previewImage} />
//   <RichTextEditor ref={this.richTextEditor}/>